﻿/****************************** Module Header ******************************\
 * Module Name:  WebDebugHelper.cs
 * Module Version:  1.0.0 (2012-05-07)
 * Copyright (c) AnyEB.Com (14507247@qq.com)
 * 
 * This class is used to process the WebDebugHelper.
 * 
 * This source is subject to the GPL License.
 * See http://www.gnu.org/licenses/gpl.html.
 * All other rights reserved.
 * 
 * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
 * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
\***************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Text.RegularExpressions;

namespace UCF.Core.Web
{
    /// <summary>
    /// Web调试助手
    /// </summary>
    public class WebDebugHelper : IDebugHelper
    {
        private string GetTableStart()
        {
            return "<table border='1' cellspacing='0' cellpadding='0'>";
        }
        private string GetTableEnd()
        {
            return "</table>";
        }
        private string GetTableRow(params object[] args)
        {
            if (args == null) return "";
            StringBuilder sb = new StringBuilder();
            sb.Append("<tr>");
            foreach (object o in args)
            {
                sb.AppendFormat("<td>{0}&nbsp;</td>", o);
            }
            sb.Append("</tr>");
            return sb.ToString();
        }
        private string GetTableHead(params string[] args)
        {
            if (args == null) return "";
            StringBuilder sb = new StringBuilder();
            sb.Append("<tr>");
            foreach (object o in args)
            {
                sb.AppendFormat("<th>{0}</th>", o);
            }
            sb.Append("</tr>");
            return sb.ToString();
        }
        /// <summary>
        /// 打印字符串
        /// </summary>
        /// <param name="s"></param>
        public void Show(string s, params object[] args)
        {
            _Response.Write(s, args);
        }

        /// <summary>
        /// 输出并停止执行后续指令
        /// </summary>
        /// <param name="isBreakLine"></param>
        /// <param name="isEnd"></param>
        /// <param name="args"></param>
        public void Show(bool isBreakLine, bool isEnd, params object[] args)
        {
            foreach (string a in args)
            {
                _Response.Write("{0}{1}".Fmt(a.ToString(),isBreakLine?"<br />":""));
            }
            if (isEnd) _Response.WriteEnd(string.Empty);
        }
        /// <summary>
        /// 打印实体类数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="e"></param>
        public void ShowType<T>(T e)
        {
            _Response.Write(GetTableStart());
            _Response.Write(GetTableHead("字段", "值", "类型"));
            foreach (PropertyInfo pi in typeof(T).GetProperties())
            {
                if (pi.CanRead) _Response.Write(GetTableRow(pi.Name, pi.GetValue(e, null), pi.PropertyType.ToString()));
            }
            _Response.Write(GetTableEnd());
        }

        /// <summary>
        /// 打印数据指令语句
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="para"></param>
        public void ShowSql(string sql, params DbParameter[] para)
        {
            Regex re;
            foreach (DbParameter p in para)
            {
                //re = new Regex("(?:(?<Test>{0})\\W|(?<Test>{0}\\Z))".Fmt(p.ParameterName));
                re = new Regex(p.ParameterName);
                if (p.DbType == DbType.Guid || p.DbType == DbType.String || p.DbType == DbType.DateTime)
                {
                    sql = re.Replace(sql, "'{0}'".Fmt(p.Value));
                }
                else
                {
                    sql = re.Replace(sql, p.Value.ToString());
                }
            }
            _Response.Write(sql);
        }

        /// <summary>
        /// 打印数据参数列表
        /// </summary>
        /// <param name="para"></param>
        /// <param name="splitor"></param>
        public void ShowDbParameters(DbParameter[] para, string splitor = "<br />")
        {
            foreach (DbParameter p in para)
            {
                if (p.DbType == DbType.Guid || p.DbType == DbType.String || p.DbType == DbType.DateTime)
                {
                    _Response.Write("{0}='{1}'{2}".Fmt(p.ParameterName, p.Value, splitor));
                }
                else
                {
                    _Response.Write("{0}={1}{2}".Fmt(p.ParameterName, p.Value, splitor));
                }
            }
        }

        /// <summary>
        /// 打印数据表
        /// </summary>
        /// <param name="dt"></param>
        public void ShowTable(DataTable dt)
        {
            if (dt == null || dt.Columns.Count == 0) return;
            
            _Response.Write(GetTableStart());
            _Response.Write("<tr>");
            foreach (DataColumn c in dt.Columns)
            {
                _Response.Write("<th>{0}</th>".Fmt(c.ColumnName));
            }
            _Response.Write("</tr>");
            foreach (DataRow r in dt.Rows)
            {
                _Response.Write("<tr>");
                foreach (object s in r.ItemArray)
                {
                    _Response.Write("<td>{0}&nbsp;</td>".Fmt(s));
                }
                _Response.Write("</tr>");
            }
            _Response.Write(GetTableEnd());
        }

        /// <summary>
        /// 打印键值集合
        /// </summary>
        /// <typeparam name="K"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="dict"></param>
        public void ShowSortedDictionary<K, V>(ref SortedDictionary<K, V> dict)
        {
            foreach (K k in dict.Keys)
            {
                _Response.Write("<div>{0}={1}</div>".Fmt(k, dict[k]));
            }
        }

        /// <summary>
        /// 保存到日志
        /// </summary>
        /// <param name="logfolder"></param>
        /// <param name="msg"></param>
        public void Log(string logfolder, string msg)
        {
            FileHelper.AppendToFile(string.Format("{1}DateTime:{0}{1}{2}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Environment.NewLine, msg), string.Format("{0}\\{1}.txt", logfolder, DateTime.Today.ToString("yyyyMMdd")));
        }

        /// <summary>
        /// 打印控件
        /// </summary>
        /// <param name="controlCollection"></param>
        public void ShowControls(IList<System.Web.UI.Control> controlCollection)
        {
            _Response.Write(GetTableStart());
            foreach (System.Web.UI.Control c in controlCollection)
            {
                _Response.Write(GetTableRow(c.ID, c.GetType().Name, c.GetType().ToString()));
            }
            _Response.Write(GetTableEnd());
        }

        /// <summary>
        /// 打印控件
        /// </summary>
        /// <param name="controlCollection"></param>
        public void ShowControls(System.Web.UI.ControlCollection controlCollection)
        {
            _Response.Write(GetTableStart());
            foreach (System.Web.UI.Control c in controlCollection)
            {
                _Response.Write(GetTableRow(c.ID, c.GetType().Name, c.GetType().ToString()));
            }
            _Response.Write(GetTableEnd());
        }

        public void ShowDictionary<K, V>(Dictionary<K, V> dict)
        {
            _Response.Write(GetTableStart());
            foreach (K k in dict.Keys)
            {
                _Response.Write(GetTableRow(k, dict[k]));
            }
            _Response.Write(GetTableEnd());
        }


        public void ShowEnd(string s="",params object[] args)
        {
            _Response.WriteEnd(s,args);
        }
    }
}
